package top.blackr.weather;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.dreamlu.mica.http.HttpRequest;
import top.blackr.config.*;
import top.blackr.egg.EasterEgg;

/**
 * 天气模板
 *
 * @author BlackR
 */
public class WeatherTemplate<R> implements Template<WeatherParamsData> {

    private static final String MSG_TEMPLATE_ID = "mWzTFPQqHEiCaoHzjv2kYi9W42RhqI3zEYOpq9MR92Q";

    @Override
    public void sendMessage(WeatherParamsData paramsData) {
        // 101010100
        if (ObjectUtil.isEmpty(paramsData) || ObjectUtil.isEmpty(paramsData.getCityId())) {
            return;
        }
        // 获取天气数据
        WeatherDataSource dataSource = (WeatherDataSource) this.dataSource(paramsData);
        // 获取沙雕文案
        dataSource.setTitle(EasterEgg.getShaDiaoText());
        // 彩虹屁
        dataSource.setNoteCn(EasterEgg.getOneTalk());
        dataSource.setName(paramsData.getName());
        // 生日
        dataSource.setAge(Utils.getAge(paramsData.getBirthday()) + 1);
        dataSource.setBirthdayCountdown(Utils.getCountDown(paramsData.getBirthday()));
        // 发送模板消息
        MsgUtils.sendWeChatMsg(MSG_TEMPLATE_ID, paramsData.getOpenId(), dataSource);
    }

    @Override
    public DataSource dataSource(WeatherParamsData paramsData) {
        String url = "http://d1.weather.com.cn/sk_2d/%s.html?_=%s";
        String cityId = paramsData.getCityId();
        long timeMillis = System.currentTimeMillis();
        // 获取天气
        String resultData = HttpRequest.get(String.format(url, cityId, timeMillis))
                .addHeader("Referer", "http://www.weather.com.cn/")
                .execute().asString();
        String dataStr = resultData.split("=")[1];
        JSONObject dataJson = JSONUtil.parseObj(dataStr);
        return JSONUtil.toBean(dataJson, WeatherDataSource.class);
    }
}
